import { Controller, Post, Body, UnauthorizedException, Get, Put, Param, Query, UseGuards, Delete } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LoginDto, LoginResponseDto } from './dto/login.dto';
import { RegisterDto, RegisterResponseDto } from './dto/register.dto';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
import { UserQueryDto, UserEditDto, UserInfoDto, UserListResponseDto } from './dto/user.dto';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { RolesGuard } from './guards/roles.guard';
import { Roles } from './decorators/roles.decorator';
import { CurrentUser } from './decorators/current-user.decorator';
import { UserRole } from './enums/user.enum';
import { User } from './entities/user.entity';

@ApiTags('认证')
@Controller('auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  @Post('register')
  @ApiOperation({ summary: '用户注册', description: '注册新用户账号' })
  @ApiResponse({ status: 201, description: '注册成功', type: RegisterResponseDto })
  @ApiResponse({ status: 400, description: '请求参数错误' })
  @ApiResponse({ status: 409, description: '用户名或邮箱已存在' })
  async register(@Body() registerDto: RegisterDto) {
    const user = await this.authService.register(
      registerDto.username,
      registerDto.email,
      registerDto.password,
      registerDto.phone,
    );
    return {
      success: true,
      message: '注册成功',
    };
  }

  @Post('login')
  @ApiOperation({ summary: '用户登录', description: '使用用户名和密码登录系统' })
  @ApiResponse({ status: 200, description: '登录成功', type: LoginResponseDto })
  @ApiResponse({ status: 401, description: '用户名或密码错误' })
  async login(@Body() loginDto: LoginDto) {
    console.log(loginDto); // 打印登录请求体
    const user = await this.authService.validateUser(
      loginDto.username,
      loginDto.password,
    );
    if (!user) {
      throw new UnauthorizedException('用户名或密码错误');
    }
    return this.authService.login(user);
  }

  @Get('profile')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取当前用户信息', description: '获取已登录用户的详细信息' })
  @ApiResponse({ status: 200, description: '获取成功', type: UserInfoDto })
  @ApiResponse({ status: 401, description: '未授权' })
  async getProfile(@CurrentUser() user: any) {
    return this.authService.getUserProfile(user.id);
  }

  @Get('users')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取用户列表', description: '获取所有用户信息，支持分页' })
  @ApiResponse({ status: 200, description: '获取成功', type: UserListResponseDto })
  @ApiResponse({ status: 401, description: '未授权' })
  async getUsers(@Query() query: UserQueryDto) {
    return this.authService.getUsers(query);
  }

  @Put('users/:id')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '编辑用户信息', description: '编辑指定用户的信息' })
  @ApiResponse({ status: 200, description: '编辑成功', type: UserInfoDto })
  @ApiResponse({ status: 401, description: '未授权' })
  @ApiResponse({ status: 403, description: '无权修改' })
  @ApiResponse({ status: 404, description: '用户不存在' })
  async updateUser(
    @Param('id') id: string,
    @Body() updateUserDto: UserEditDto,
    @CurrentUser() currentUser: User,
  ) {
    return this.authService.updateUser(parseInt(id), updateUserDto, currentUser);
  }

  @Delete('users/:id')
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN)
  @ApiBearerAuth()
  @ApiOperation({ summary: '删除用户', description: '删除指定用户（仅管理员可用）' })
  @ApiResponse({ status: 200, description: '删除成功' })
  @ApiResponse({ status: 401, description: '未授权' })
  @ApiResponse({ status: 403, description: '无权删除' })
  @ApiResponse({ status: 404, description: '用户不存在' })
  async deleteUser(
    @Param('id') id: string,
    @CurrentUser() currentUser: User,
  ) {
    await this.authService.deleteUser(parseInt(id), currentUser);
    return { message: '删除成功' };
  }
} 